<template>
  <form class="validate-form-container">
    <slot name="default"></slot>
    <div class="submit-area" @click.prevent="submitForm">
      <slot name="submit">
        <button type="submit" class="btn btn-primary">提交</button>
      </slot>
    </div>
  </form>
</template>

<script lang="ts">
import { defineComponent, onUnmounted } from "vue";
import { ValidateFunc } from "@/types";
import mitt from "mitt"; // https://github.com/developit/mitt

export const emitter = mitt<{ formItemCreated: ValidateFunc }>();

export default defineComponent({
  name: "ValidateForm",
  emits: ["form-submit"],
  setup(_, { emit }) {
    let funcArr: ValidateFunc[] = [];

    // 父组件监听子组件事件
    const callback = (func: ValidateFunc) => {
      funcArr.push(func);
    };
    emitter.on("formItemCreated", callback);

    const submitForm = () => {
      const result = funcArr.map((func) => func()).every((res) => res);
      emit("form-submit", result);
    };

    onUnmounted(() => {
      emitter.off("formItemCreated", callback);
      funcArr = [];
    });

    return {
      submitForm,
    };
  },
});
</script>
